<template>
  <div class="bg-f2">
    <div class="bg-f2 bg-fff">
      <ul class="addMargin">
        <li>
          <el-button class="addRole btnSizeStyle" :disabled="quanxianBtns.btn1" icon="el-icon-plus" @click="addRole('添加资产字典')">添加</el-button>
        </li>
        <li>
          <div class="select">
            <span style="margin-right: 5px">名称:</span>
            <el-input clearable v-model.trim="unitList" placeholder="请输入" class="input_name"></el-input>
          </div>
        </li>
        <li>
          <el-button type="primary" class="max_btn2 btnSizeStyle" @click="searchBtn2()">查询</el-button>
        </li>
      </ul>
      <el-drawer title="我是标题" :visible.sync="increased" :with-header="false" :wrapperClosable="false">
        <div class="addUer_title">
          <span>{{ title }}</span>
          <i class="el-icon-close addUer_icon" @click="offDrawer('ruleForm')"></i>
        </div>
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px">
          <el-row>
            <el-col :span="23">
              <el-form-item label="字典名称：" prop="lxmc">
                <el-input v-model.trim="ruleForm.lxmc" clearable placeholder="请输入字典名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="23">
              <el-form-item label="父级字典名称：">
                <el-cascader v-model.trim="ruleForm.flxid" :options="jgmcOptions" :props="{ checkStrictly: true }" filterable clearable class="zidainWidth"></el-cascader>
              </el-form-item>
            </el-col>
          </el-row>
          <div class="forms_fooer">
            <el-button class="users_btn btnSizeStyle" @click="offDrawer('ruleForm')">取消</el-button>
            <el-button type="primary" class="users_btn btnSizeStyle" @click="submitForm(title, 'ruleForm')" v-preventReClick>确定</el-button>
          </div>
        </el-form>
      </el-drawer>
      <el-card>
        <el-table
          :header-cell-style="{ backgroundColor: '#ECF3FC', color: '#333', height: '48px', borderBottom: '1px solid #CEE1F7' }"
          ref="multipleTable"
          :data="roleList"
          stripe
          border
          style="width: 100%"
          highlight-current-row
          :row-key="getRowKeys"
          :expand-row-keys="expands"
          @row-dblclick="rowClick"
          v-loading="tableLoad"
        >
          <!-- @expand-change="tabsChange" -->
          <!-- :row-class-name="getRowClass" -->
          <!-- :row-key="getRowKeys"
          :expand-row-keys="expands"-->
          <!-- <el-table-column type="expand">
          <template>
            <el-tree
              :data="dataBm"
              node-key="id"
              :expand-on-click-node="true"
              icon-class="el-icon-arrow-right"
              :default-expanded-keys="sxsj"
              style="margin-left: 15px;"
            >
              <span class="column_item" slot-scope="{ node, data }">
                <span>{{ node.label }}</span>
                <span>
                  <el-tag type="warning" size="small">资产类型</el-tag>
                </span>
                <span>{{ data.tjsj | dateFormat }}</span>
                <span>
                  <el-button type="text" @click="addRole('编辑资产字典', data)">编辑</el-button>
                  <span class="operation"></span>
                  <el-button type="text" class="color_f56f6f" @click="deteleRole(data)">删除</el-button>
                </span>
              </span>
            </el-tree>
          </template>
          </el-table-column>-->
          <!-- 提示语句 -->
          <template slot="empty">{{ tableMessage }}</template>

          <el-table-column type="index" label="序号" min-width="50" align="center"></el-table-column>
          <el-table-column prop="lxmc" label="名称" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="rd" label="字典类别">
            <el-tag type="success" size="small">资产类型</el-tag>
          </el-table-column>
          <el-table-column label="添加人" prop="createBy" min-width="100"></el-table-column>
          <el-table-column prop="CJSJ" label="添加时间">
            <template slot-scope="scope">
              <span>{{ scope.row.tjsj | dateFormat }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="right">
            <template slot-scope="scope">
              <el-button type="text" :disabled="quanxianBtns.btn2" @click="addRole('编辑资产字典', scope.row)">编辑</el-button>
              <span class="operation" v-show="scope.row.scbs - '' === 0 ? true : false"></span>
              <el-button type="text" class="color_f56f6f" :disabled="quanxianBtns.btn3" v-show="scope.row.scbs - '' === 0 ? true : false" @click="deteleRole(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-dialog title="删除" :visible.sync="dialogVisible" width="30%">
          <span>您确定要删除吗？</span>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="deleteItem2" v-preventReClick>确 定</el-button>
          </span>
        </el-dialog>
        <div class="pageFloat">
          <div></div>
          <el-pagination
            background
            small
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next"
            :total="total"
          ></el-pagination>
        </div>
      </el-card>
    </div>
  </div>
</template>
<script>
import { ziC } from '@/utils/allUrl.js'
// import { endLoading } from '../../utils/loading.js'
import { getUrl } from '@/utils/getUrl.js'
import { timeLoad, tableMessageText } from '@/assets/js/setTime'

export default {
  data: function () {
    return {
      currentPage: 1,
      pageSize: 10,
      roleList: [],
      total: 0,
      jgmcOptions: [], // 字典类别数据源
      dialogVisible: false,
      unitList: '', // 字典类别
      ruleForm: {
        lxmc: '',
        flxid: '',
      },
      rules: {
        lxmc: [
          { required: true, message: '此处为必填项', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
        ],
      },
      deleteID: '', // 删除的id
      increased: false, // 添加分组对话框
      title: '添加资产分组',
      // dataBm: [], // 展开树
      // 行数据的Key
      getRowKeys(row) {
        return row.id
      },
      expands: [],
      sxsj: [],
      tableLoad: false,
      tableTimer: null,
      tableMessage: '',
      quanxianBtns: {
        btn1: true,
        btn2: true,
        btn3: true,
      },
    }
  },
  watch: {
    tableLoad(newVal, oldVal) {
      this.tableTimer = setTimeout(() => {
        if (this.tableLoad) {
          this.tableLoad = false
          this.roleList = []
          this.tableMessage = tableMessageText
          // this.total = 0
        }
      }, timeLoad)
    },
  },
  created: function () {
    this.getList()
    this.jurisdictionBtn()
  },
  methods: {
    // 获取按钮权限
    jurisdictionBtn() {
      const menus = JSON.parse(getUrl('jurisdiction'))
      menus.forEach((item) => {
        if (item.qxdm === 'ZCZX_ZCGL_ZCLXZD') {
          item.children.forEach((item2) => {
            if (item2.qxdm === 'zczd:create') {
              this.quanxianBtns.btn1 = false // 添加
            } else if (item2.qxdm === 'zczd:update') {
              this.quanxianBtns.btn2 = false // 修改
            } else if (item2.qxdm === 'zczd:delete') {
              this.quanxianBtns.btn3 = false // 删除
            }
          })
        }
      })
    },
    // 获取数据
    getList() {
      clearTimeout(this.tableTimer)
      this.tableLoad = true
      const params = new URLSearchParams()
      params.append('M_', this.currentPage)
      params.append('N_', this.pageSize)
      params.append('FLXID', 0)
      this.setList(params)
      // const { data: res } = await this.$http.post(`${ziC}zczd/list`, params)
      // // clearTimeout(a)
      // // endLoading()
      // if (res.code === '0013') {
      //   this.total = 0
      //   return (this.roleList = [])
      // } else if (res.code !== '0000') {
      //   return this.$message({
      //     type: 'error',
      //     message: res.message,
      //     center: true,
      //   })
      // }
      // // const arr = []
      // // res.data.list.forEach(item => {
      // //   const la = JSON.stringify(item).replace(/children/, 'xiaji')
      // //   arr.push(JSON.parse(la))
      // // })
      // this.roleList = res.data.list
      // this.total = res.data.countList
    },
    async setList(params) {
      const { data: res } = await this.$http.post(`${ziC}zczd/list`, params)
      switch (res.code) {
        case '0000':
          this.roleList = res.data.list
          this.total = res.data.countList
          break
        default:
          this.roleList = []
          this.total = 0
          this.tableMessage = res.message
          break
      }
      this.tableLoad = false // 表格加载中样式
    },
    handleClick(tab, event) {},
    handleSizeChange(newsize) {
      this.currentPage = 1
      this.pageSize = newsize
      this.searchBtn()
    },
    handleCurrentChange(newChange) {
      this.currentPage = newChange
      this.searchBtn()
    },
    // 添加/修改
    async addRole(title, scope) {
      if (scope) {
        this.ruleForm = {
          lxmc: scope.lxmc,
          flxid: scope.flxid,
          id: scope.id,
        }
        if (scope.label) {
          this.ruleForm.lxmc = scope.label
        }
      }
      const params = new URLSearchParams()
      params.append('FLXID', 0)
      const { data: res } = await this.$http.post(`${ziC}zczd/list`, params)
      if (res.code !== '0000') {
        this.jgmcOptions = []
        return this.$message({
          type: 'error',
          message: '资产' + res.message,
          center: true,
        })
      } else {
        const city = JSON.stringify(res.data.list)
        const newCity = city.replace(/id/g, 'value')
        const cityList = newCity.replace(/lxmc/g, 'label')
        const newList = []
        JSON.parse(cityList).forEach((item) => {
          if (item.children) {
            if (item.children.length < 1) {
              delete item.children
            } else {
              item.children.forEach((jtem) => {
                delete jtem.children
              })
            }
          }
          newList.push(item)
        })
        this.jgmcOptions = newList
      }
      this.title = title
      this.increased = true
    },
    // 删除
    deteleRole(scope) {
      if (scope.xiaji) {
        if (scope.xiaji.length > 0) {
          return this.$message({
            type: 'error',
            message: '该类型存在下级，不可删除！',
            center: true,
          })
        } else {
          this.deleteID = scope.id
          this.dialogVisible = true
        }
      } else if (scope.children) {
        if (scope.children.length > 0) {
          return this.$message({
            type: 'error',
            message: '该类型存在下级，不可删除！',
            center: true,
          })
        }
      } else {
        this.deleteID = scope.id
        this.dialogVisible = true
      }
    },
    async deleteItem2() {
      const params = new URLSearchParams()
      params.append('ID', this.deleteID)
      const { data: res } = await this.$http.post(`${ziC}zczd/delete`, params)
      if (res.code === '0014') {
        return ''
      } else if (res.code !== '0000') {
        return this.$message({
          type: 'error',
          message: res.message,
          center: true,
        })
      }
      this.$message({
        type: 'success',
        message: res.message,
        center: true,
      })
      this.dialogVisible = false
      this.getList()
      this.expands = []
      this.sxsj = [this.deleteID]
    },
    // 取消按钮
    offDrawer(ruleForm) {
      this.$refs.ruleForm.resetFields()
      this.increased = false
      this.ruleForm = {
        lxmc: '',
        flxid: '',
      }
      this.getList()
    },
    // 提交按钮
    submitForm(title, ruleForm) {
      const { lxmc, flxid, id } = this.ruleForm
      const params = new URLSearchParams()
      params.append('LXMC', lxmc)
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (title === '添加资产字典') {
            params.append('FLXID', flxid[flxid.length - 1] || 0)
            const { data: res } = await this.$http.post(`${ziC}zczd/create`, params)
            if (res.code === '0014') {
              return ''
            } else if (res.code !== '0000') {
              return this.$message({
                type: 'error',
                message: res.message,
                center: true,
              })
            }
            this.$message({
              type: 'success',
              message: res.message,
              center: true,
            })
            this.increased = false
            this.getList()
            this.expands = []
            this.ruleForm = {
              lxmc: '',
              flxid: '',
            }
          } else {
            params.append('ID', id)
            if (typeof flxid !== 'number') {
              params.append('FLXID', flxid[flxid.length - 1] || 0)
            } else {
              params.append('FLXID', flxid || '')
            }
            const { data: res } = await this.$http.post(`${ziC}zczd/update`, params)
            if (res.code === '0014') {
              return ''
            } else if (res.code !== '0000') {
              return this.$message({
                type: 'error',
                message: res.message,
                center: true,
              })
            }
            this.$message({
              type: 'success',
              message: res.message,
              center: true,
            })
            this.increased = false
            this.getList()
            this.expands = []
            this.sxsj = [id]
            this.ruleForm = {
              lxmc: '',
              flxid: '',
            }
          }
        } else {
          this.$message({
            type: 'error',
            message: '请填写正确的信息',
            center: true,
          })
          return false
        }
      })
    },
    // 展开获取部门
    tabsChange(selection, evt) {
      const a = this.expands.findIndex((item) => item === selection.id)
      if (a !== -1) {
        this.expands.splice(a, 1)
      } else {
        this.expands = []
        if (selection) {
          this.expands.push(selection.id)
        }
      }
      // const la = JSON.stringify(selection.xiaji).replace(/lxmc/g, 'label')
      // this.dataBm = JSON.parse(la)
    },
    searchBtn2() {
      this.currentPage = 1
      this.pageSize = 10
      this.searchBtn()
    },
    // 查询
    async searchBtn() {
      clearTimeout(this.tableTimer)
      this.tableLoad = true
      const params = new URLSearchParams()
      params.append('LXMC', this.unitList)
      params.append('FLXID', 0)
      params.append('M_', this.currentPage)
      params.append('N_', this.pageSize)
      this.setList(params)
      // const { data: res } = await this.$http.post(`${ziC}zczd/list`, params)
      // if (res.code === '0014') {
      //   return ''
      // } else if (res.code !== '0000') {
      //   this.roleList = []
      //   return this.$message({
      //     type: 'error',
      //     message: res.message,
      //     center: true,
      //   })
      // }
      // const arr = []
      // res.data.list.forEach(item => {
      //   const la = JSON.stringify(item).replace(/children/, 'xiaji')
      //   arr.push(JSON.parse(la))
      // })
      // this.roleList = res.data.list
      // this.total = res.data.countList
    },
    // 展开
    rowClick(row, column, event) {
      this.tabsChange(row)
    },
    // 判断表格是否有子项，无子项不显示展开按钮
    getRowClass({ row, rowIndex }) {
      if (!row.xiaji || row.xiaji.length <= 0) {
        return 'row-expand-cover'
      }
    },
  },
}
</script>
<style lang="scss" scoped>
.addMargin {
  margin-bottom: 15px;
  height: 35px;
  line-height: 35px;
  display: flex;
  > li:first-child {
    margin-left: 0;
  }
  > li {
    margin-left: 10px;
    .addRole {
      background: rgba(103, 194, 58, 1);
      font-size: 14px;
      color: #fff;
      text-align: center;
    }
    .select {
      display: flex;
      .input_name {
        width: 250px;
      }
    }
  }
}
.operation {
  display: inline-block;
  margin: 0 5px;
  height: 10px;
  border-left: 1.5px solid #b3b3b3;
}
.usersNumber {
  color: rgba(46, 146, 247, 1);
}
.el-card {
  border-radius: 0;
}
.el-drawer {
  .addUer_title {
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    height: 61px;
    line-height: 61px;
    border-bottom: 1px solid #ededed;
    box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.8);
    > span {
      font-size: 18px;
      font-weight: 600;
    }
    .addUer_icon {
      font-size: 20px;
      font-weight: 700;
      display: flex;
      flex-flow: column;
      justify-content: center;
      cursor: pointer;
    }
  }
  .zidainWidth {
    width: 260px;
  }
  .el-row {
    margin-top: 30px;
  }
  .forms_fooer {
    position: absolute;
    bottom: 0;
    width: 100%;
    display: flex;
    justify-content: flex-end;
    padding: 0 20px;
    box-sizing: border-box;
    align-items: center;
    height: 61px;
    line-height: 61px;
    border-top: 1px solid #ededed;
  }
}
.column_item {
  display: inline-block;
  width: 100%;
  padding-right: 10px;
  height: 40px;
  line-height: 40px;
  position: relative;
  > span {
    float: left;
  }
  > span:nth-child(1) {
    margin-left: 1.2%;
  }
  > span:nth-child(2) {
    position: absolute;
    left: 26%;
  }
  > span:nth-child(3) {
    position: absolute;
    left: 50.85%;
  }
  > span:nth-child(4) {
    float: right;
  }
}
.pageFloat {
  width: 100%;
  padding: 10px 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .shoujiBtn {
    margin-left: 15px;
    height: 35px;
  }
}
</style>
